//! # 应用性能监控 (APM) 模块
//!
//! 提供企业级的应用性能监控、瓶颈识别和慢查询捕获功能

use crate::{MetricFamily, Metric, MetricValue, Labels};
use rustcloud_core::{ServiceResult, ServiceError};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::{RwLock, mpsc};
use async_trait::async_trait;
use tracing::{debug, info, warn, error, instrument};
use uuid::Uuid;

/// APM 配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApmConfig {
    /// 是否启用 APM
    pub enabled: bool,
    /// 慢查询阈值
    pub slow_query_threshold: Duration,
    /// 性能采样率
    pub sampling_rate: f64,
    /// 最大性能事件数量
    pub max_performance_events: usize,
    /// 瓶颈检测配置
    pub bottleneck_detection: BottleneckDetectionConfig,
    /// 异常检测配置
    pub anomaly_detection: AnomalyDetectionConfig,
    /// 报告间隔
    pub reporting_interval: Duration,
}

/// 瓶颈检测配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BottleneckDetectionConfig {
    /// 是否启用
    pub enabled: bool,
    /// CPU 使用率阈值
    pub cpu_threshold: f64,
    /// 内存使用率阈值
    pub memory_threshold: f64,
    /// 响应时间阈值
    pub response_time_threshold: Duration,
    /// 错误率阈值
    pub error_rate_threshold: f64,
    /// 检测时间窗口
    pub detection_window: Duration,
}

/// 异常检测配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnomalyDetectionConfig {
    /// 是否启用
    pub enabled: bool,
    /// 异常检测算法
    pub algorithm: AnomalyDetectionAlgorithm,
    /// 检测敏感度
    pub sensitivity: f64,
    /// 历史数据窗口
    pub history_window: Duration,
    /// 最小样本数
    pub min_samples: usize,
}

/// 异常检测算法
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AnomalyDetectionAlgorithm {
    /// 标准差
    StandardDeviation,
    /// 移动平均
    MovingAverage,
    /// 统计分析
    Statistical,
    /// 机器学习
    MachineLearning,
}

impl Default for ApmConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            slow_query_threshold: Duration::from_millis(1000),
            sampling_rate: 0.1, // 10% 采样
            max_performance_events: 10000,
            bottleneck_detection: BottleneckDetectionConfig::default(),
            anomaly_detection: AnomalyDetectionConfig::default(),
            reporting_interval: Duration::from_secs(60),
        }
    }
}

impl Default for BottleneckDetectionConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            cpu_threshold: 80.0,
            memory_threshold: 85.0,
            response_time_threshold: Duration::from_millis(5000),
            error_rate_threshold: 5.0,
            detection_window: Duration::from_secs(300),
        }
    }
}

impl Default for AnomalyDetectionConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            algorithm: AnomalyDetectionAlgorithm::StandardDeviation,
            sensitivity: 2.0,
            history_window: Duration::from_secs(3600),
            min_samples: 30,
        }
    }
}

/// 性能事件
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceEvent {
    /// 事件ID
    pub id: String,
    /// 事件类型
    pub event_type: PerformanceEventType,
    /// 服务名称
    pub service_name: String,
    /// 操作名称
    pub operation: String,
    /// 开始时间
    pub start_time: SystemTime,
    /// 结束时间
    pub end_time: Option<SystemTime>,
    /// 持续时间
    pub duration: Option<Duration>,
    /// 状态
    pub status: PerformanceStatus,
    /// 错误信息
    pub error: Option<String>,
    /// 标签
    pub labels: HashMap<String, String>,
    /// 指标数据
    pub metrics: HashMap<String, f64>,
    /// 堆栈跟踪
    pub stack_trace: Option<String>,
}

/// 性能事件类型
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum PerformanceEventType {
    /// HTTP 请求
    HttpRequest,
    /// 数据库查询
    DatabaseQuery,
    /// 外部服务调用
    ExternalServiceCall,
    /// 内部方法调用
    MethodCall,
    /// 系统资源使用
    SystemResource,
    /// 业务操作
    BusinessOperation,
}

/// 性能状态
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum PerformanceStatus {
    /// 成功
    Success,
    /// 失败
    Error,
    /// 超时
    Timeout,
    /// 正在进行
    InProgress,
}

/// 瓶颈报告
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BottleneckReport {
    /// 报告ID
    pub id: String,
    /// 检测时间
    pub detected_at: SystemTime,
    /// 瓶颈类型
    pub bottleneck_type: BottleneckType,
    /// 严重级别
    pub severity: BottleneckSeverity,
    /// 描述
    pub description: String,
    /// 影响的服务
    pub affected_services: Vec<String>,
    /// 建议
    pub recommendations: Vec<String>,
    /// 相关指标
    pub metrics: HashMap<String, f64>,
}

/// 瓶颈类型
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum BottleneckType {
    /// CPU 瓶颈
    Cpu,
    /// 内存瓶颈
    Memory,
    /// 网络瓶颈
    Network,
    /// 磁盘 I/O 瓶颈
    DiskIo,
    /// 数据库瓶颈
    Database,
    /// 外部依赖瓶颈
    ExternalDependency,
    /// 算法瓶颈
    Algorithm,
}

/// 瓶颈严重级别
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum BottleneckSeverity {
    /// 低
    Low,
    /// 中等
    Medium,
    /// 高
    High,
    /// 严重
    Critical,
}

/// APM 管理器
pub struct ApmManager {
    config: ApmConfig,
    performance_events: Arc<RwLock<VecDeque<PerformanceEvent>>>,
    bottleneck_reports: Arc<RwLock<Vec<BottleneckReport>>>,
    active_transactions: Arc<RwLock<HashMap<String, PerformanceEvent>>>,
    metrics_aggregator: Arc<RwLock<MetricsAggregator>>,
    anomaly_detector: Arc<RwLock<AnomalyDetector>>,
    event_sender: Option<mpsc::UnboundedSender<PerformanceEvent>>,
}

/// 指标聚合器
#[derive(Debug)]
pub struct MetricsAggregator {
    /// 响应时间直方图
    response_time_histogram: HashMap<String, Vec<f64>>,
    /// 错误计数
    error_count: HashMap<String, u64>,
    /// 吞吐量计数
    throughput_count: HashMap<String, u64>,
    /// 系统资源使用率
    resource_usage: HashMap<String, f64>,
    /// 最后更新时间
    last_updated: SystemTime,
}

/// 异常检测器
#[derive(Debug)]
pub struct AnomalyDetector {
    /// 历史数据
    history: HashMap<String, VecDeque<f64>>,
    /// 异常阈值
    thresholds: HashMap<String, f64>,
    /// 检测器配置
    config: AnomalyDetectionConfig,
}

impl ApmManager {
    /// 创建新的 APM 管理器
    pub fn new(config: ApmConfig) -> Self {
        Self {
            config: config.clone(),
            performance_events: Arc::new(RwLock::new(VecDeque::new())),
            bottleneck_reports: Arc::new(RwLock::new(Vec::new())),
            active_transactions: Arc::new(RwLock::new(HashMap::new())),
            metrics_aggregator: Arc::new(RwLock::new(MetricsAggregator::new())),
            anomaly_detector: Arc::new(RwLock::new(AnomalyDetector::new(config.anomaly_detection))),
            event_sender: None,
        }
    }

    /// 启动 APM 管理器
    pub async fn start(&mut self) -> ServiceResult<()> {
        if !self.config.enabled {
            info!("APM is disabled");
            return Ok(());
        }

        info!("Starting APM manager");

        // 创建事件处理器
        let (tx, mut rx) = mpsc::unbounded_channel::<PerformanceEvent>();
        self.event_sender = Some(tx);

        // 启动事件处理循环
        let events = self.performance_events.clone();
        let aggregator = self.metrics_aggregator.clone();
        let detector = self.anomaly_detector.clone();
        let config = self.config.clone();

        tokio::spawn(async move {
            while let Some(event) = rx.recv().await {
                // 存储事件
                let mut events_queue = events.write().await;
                events_queue.push_back(event.clone());
                
                // 保持队列大小
                if events_queue.len() > config.max_performance_events {
                    events_queue.pop_front();
                }
                drop(events_queue);

                // 更新指标聚合器
                aggregator.write().await.update_metrics(&event);

                // 异常检测
                if config.anomaly_detection.enabled {
                    if let Some(duration) = event.duration {
                        detector.write().await.detect_anomaly(&event.operation, duration.as_millis() as f64);
                    }
                }
            }
        });

        // 启动瓶颈检测循环
        if self.config.bottleneck_detection.enabled {
            self.start_bottleneck_detection().await?;
        }

        // 启动报告生成循环
        self.start_reporting().await?;

        Ok(())
    }

    /// 开始性能事务
    #[instrument(skip(self))]
    pub async fn start_transaction(&self, service_name: &str, operation: &str, event_type: PerformanceEventType) -> ServiceResult<String> {
        if !self.config.enabled {
            return Ok(String::new());
        }

        let transaction_id = Uuid::new_v4().to_string();
        let event = PerformanceEvent {
            id: transaction_id.clone(),
            event_type,
            service_name: service_name.to_string(),
            operation: operation.to_string(),
            start_time: SystemTime::now(),
            end_time: None,
            duration: None,
            status: PerformanceStatus::InProgress,
            error: None,
            labels: HashMap::new(),
            metrics: HashMap::new(),
            stack_trace: None,
        };

        self.active_transactions.write().await.insert(transaction_id.clone(), event);
        debug!("Started transaction: {} for {}", transaction_id, operation);

        Ok(transaction_id)
    }

    /// 结束性能事务
    #[instrument(skip(self))]
    pub async fn end_transaction(&self, transaction_id: &str, status: PerformanceStatus, error: Option<String>) -> ServiceResult<()> {
        if !self.config.enabled || transaction_id.is_empty() {
            return Ok(());
        }

        let mut active_transactions = self.active_transactions.write().await;
        if let Some(mut event) = active_transactions.remove(transaction_id) {
            let end_time = SystemTime::now();
            event.end_time = Some(end_time);
            event.duration = end_time.duration_since(event.start_time).ok();
            event.status = status;
            event.error = error;

            // 检查是否为慢查询
            if let Some(duration) = event.duration {
                if duration > self.config.slow_query_threshold {
                    warn!("Slow operation detected: {} took {:?}", event.operation, duration);
                    event.labels.insert("slow_query".to_string(), "true".to_string());
                }
            }

            debug!("Ended transaction: {} for {}", transaction_id, event.operation);

            // 发送事件到处理器
            if let Some(sender) = &self.event_sender {
                let _ = sender.send(event);
            }
        }

        Ok(())
    }

    /// 添加事务标签
    pub async fn add_transaction_label(&self, transaction_id: &str, key: &str, value: &str) -> ServiceResult<()> {
        if !self.config.enabled || transaction_id.is_empty() {
            return Ok(());
        }

        let mut active_transactions = self.active_transactions.write().await;
        if let Some(event) = active_transactions.get_mut(transaction_id) {
            event.labels.insert(key.to_string(), value.to_string());
        }

        Ok(())
    }

    /// 添加事务指标
    pub async fn add_transaction_metric(&self, transaction_id: &str, name: &str, value: f64) -> ServiceResult<()> {
        if !self.config.enabled || transaction_id.is_empty() {
            return Ok(());
        }

        let mut active_transactions = self.active_transactions.write().await;
        if let Some(event) = active_transactions.get_mut(transaction_id) {
            event.metrics.insert(name.to_string(), value);
        }

        Ok(())
    }

    /// 记录系统资源使用
    pub async fn record_system_resource(&self, resource_name: &str, usage_percent: f64) -> ServiceResult<()> {
        if !self.config.enabled {
            return Ok(());
        }

        self.metrics_aggregator.write().await.update_resource_usage(resource_name, usage_percent);

        // 检查瓶颈
        if self.config.bottleneck_detection.enabled {
            self.check_resource_bottleneck(resource_name, usage_percent).await?;
        }

        Ok(())
    }

    /// 获取性能统计
    pub async fn get_performance_stats(&self) -> PerformanceStats {
        let events = self.performance_events.read().await;
        let aggregator = self.metrics_aggregator.read().await;

        let total_events = events.len();
        let error_events = events.iter().filter(|e| e.status == PerformanceStatus::Error).count();
        let success_events = events.iter().filter(|e| e.status == PerformanceStatus::Success).count();
        
        let avg_response_time = if success_events > 0 {
            events.iter()
                .filter(|e| e.status == PerformanceStatus::Success)
                .filter_map(|e| e.duration)
                .map(|d| d.as_millis() as f64)
                .sum::<f64>() / success_events as f64
        } else {
            0.0
        };

        let error_rate = if total_events > 0 {
            (error_events as f64 / total_events as f64) * 100.0
        } else {
            0.0
        };

        PerformanceStats {
            total_events,
            success_events,
            error_events,
            avg_response_time,
            error_rate,
            slow_queries: events.iter().filter(|e| e.labels.contains_key("slow_query")).count(),
            last_updated: aggregator.last_updated,
        }
    }

    /// 获取瓶颈报告
    pub async fn get_bottleneck_reports(&self) -> Vec<BottleneckReport> {
        self.bottleneck_reports.read().await.clone()
    }

    /// 检查资源瓶颈
    async fn check_resource_bottleneck(&self, resource_name: &str, usage_percent: f64) -> ServiceResult<()> {
        let bottleneck_type = match resource_name.to_lowercase().as_str() {
            "cpu" if usage_percent > self.config.bottleneck_detection.cpu_threshold => Some(BottleneckType::Cpu),
            "memory" if usage_percent > self.config.bottleneck_detection.memory_threshold => Some(BottleneckType::Memory),
            _ => None,
        };

        if let Some(bt) = bottleneck_type {
            let severity = if usage_percent >= 95.0 {
                BottleneckSeverity::Critical
            } else if usage_percent >= 90.0 {
                BottleneckSeverity::High
            } else if usage_percent >= 85.0 {
                BottleneckSeverity::Medium
            } else {
                BottleneckSeverity::Low
            };

            let report = BottleneckReport {
                id: Uuid::new_v4().to_string(),
                detected_at: SystemTime::now(),
                bottleneck_type: bt.clone(),
                severity,
                description: format!("{} usage is {}%", resource_name, usage_percent),
                affected_services: vec!["all".to_string()],
                recommendations: self.get_bottleneck_recommendations(&bt),
                metrics: {
                    let mut metrics = HashMap::new();
                    metrics.insert(format!("{}_usage", resource_name), usage_percent);
                    metrics
                },
            };

            warn!("Bottleneck detected: {:?}", report);
            self.bottleneck_reports.write().await.push(report);
        }

        Ok(())
    }

    /// 获取瓶颈建议
    fn get_bottleneck_recommendations(&self, bottleneck_type: &BottleneckType) -> Vec<String> {
        match bottleneck_type {
            BottleneckType::Cpu => vec![
                "检查CPU密集型操作".to_string(),
                "考虑水平扩展".to_string(),
                "优化算法复杂度".to_string(),
                "使用缓存减少计算".to_string(),
            ],
            BottleneckType::Memory => vec![
                "检查内存泄漏".to_string(),
                "优化数据结构".to_string(),
                "增加可用内存".to_string(),
                "实现内存池".to_string(),
            ],
            BottleneckType::Network => vec![
                "检查网络延迟".to_string(),
                "优化数据传输".to_string(),
                "使用CDN".to_string(),
                "压缩传输数据".to_string(),
            ],
            BottleneckType::Database => vec![
                "优化SQL查询".to_string(),
                "添加数据库索引".to_string(),
                "使用连接池".to_string(),
                "考虑读写分离".to_string(),
            ],
            _ => vec!["联系系统管理员".to_string()],
        }
    }

    /// 启动瓶颈检测
    async fn start_bottleneck_detection(&self) -> ServiceResult<()> {
        // TODO: 实现定期瓶颈检测逻辑
        info!("Started bottleneck detection");
        Ok(())
    }

    /// 启动报告生成
    async fn start_reporting(&self) -> ServiceResult<()> {
        // TODO: 实现定期报告生成逻辑
        info!("Started performance reporting");
        Ok(())
    }
}

/// 性能统计
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceStats {
    /// 总事件数
    pub total_events: usize,
    /// 成功事件数
    pub success_events: usize,
    /// 错误事件数
    pub error_events: usize,
    /// 平均响应时间（毫秒）
    pub avg_response_time: f64,
    /// 错误率（百分比）
    pub error_rate: f64,
    /// 慢查询数量
    pub slow_queries: usize,
    /// 最后更新时间
    pub last_updated: SystemTime,
}

impl MetricsAggregator {
    fn new() -> Self {
        Self {
            response_time_histogram: HashMap::new(),
            error_count: HashMap::new(),
            throughput_count: HashMap::new(),
            resource_usage: HashMap::new(),
            last_updated: SystemTime::now(),
        }
    }

    fn update_metrics(&mut self, event: &PerformanceEvent) {
        self.last_updated = SystemTime::now();

        // 更新吞吐量
        *self.throughput_count.entry(event.operation.clone()).or_insert(0) += 1;

        // 更新错误计数
        if event.status == PerformanceStatus::Error {
            *self.error_count.entry(event.operation.clone()).or_insert(0) += 1;
        }

        // 更新响应时间
        if let Some(duration) = event.duration {
            self.response_time_histogram
                .entry(event.operation.clone())
                .or_insert_with(Vec::new)
                .push(duration.as_millis() as f64);
        }
    }

    fn update_resource_usage(&mut self, resource_name: &str, usage: f64) {
        self.resource_usage.insert(resource_name.to_string(), usage);
        self.last_updated = SystemTime::now();
    }
}

impl AnomalyDetector {
    fn new(config: AnomalyDetectionConfig) -> Self {
        Self {
            history: HashMap::new(),
            thresholds: HashMap::new(),
            config,
        }
    }

    fn detect_anomaly(&mut self, metric_name: &str, value: f64) -> bool {
        let history = self.history.entry(metric_name.to_string()).or_insert_with(VecDeque::new);
        
        // 添加新值
        history.push_back(value);
        
        // 保持历史窗口大小
        if history.len() > self.config.min_samples * 2 {
            history.pop_front();
        }

        // 如果样本不足，不进行检测
        if history.len() < self.config.min_samples {
            return false;
        }

        // 使用标准差检测异常
        match self.config.algorithm {
            AnomalyDetectionAlgorithm::StandardDeviation => {
                let mean = history.iter().sum::<f64>() / history.len() as f64;
                let variance = history.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / history.len() as f64;
                let std_dev = variance.sqrt();
                
                let threshold = mean + (std_dev * self.config.sensitivity);
                self.thresholds.insert(metric_name.to_string(), threshold);
                
                value > threshold
            }
            _ => {
                // TODO: 实现其他异常检测算法
                false
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::time::{sleep, Duration};

    #[tokio::test]
    async fn test_apm_manager_basic() {
        let config = ApmConfig::default();
        let mut manager = ApmManager::new(config);
        
        manager.start().await.unwrap();

        // 测试事务
        let tx_id = manager.start_transaction("test-service", "test-operation", PerformanceEventType::HttpRequest).await.unwrap();
        assert!(!tx_id.is_empty());

        // 添加标签和指标
        manager.add_transaction_label(&tx_id, "user_id", "123").await.unwrap();
        manager.add_transaction_metric(&tx_id, "cpu_usage", 45.0).await.unwrap();

        // 结束事务
        sleep(Duration::from_millis(10)).await;
        manager.end_transaction(&tx_id, PerformanceStatus::Success, None).await.unwrap();

        // 等待事件处理
        sleep(Duration::from_millis(100)).await;

        // 检查统计
        let stats = manager.get_performance_stats().await;
        assert_eq!(stats.total_events, 1);
        assert_eq!(stats.success_events, 1);
        assert_eq!(stats.error_events, 0);
    }

    #[tokio::test]
    async fn test_bottleneck_detection() {
        let config = ApmConfig::default();
        let manager = ApmManager::new(config);

        // 记录高CPU使用率
        manager.record_system_resource("cpu", 95.0).await.unwrap();

        // 检查瓶颈报告
        let reports = manager.get_bottleneck_reports().await;
        assert_eq!(reports.len(), 1);
        assert_eq!(reports[0].bottleneck_type, BottleneckType::Cpu);
        assert_eq!(reports[0].severity, BottleneckSeverity::Critical);
    }

    #[tokio::test]
    async fn test_slow_query_detection() {
        let mut config = ApmConfig::default();
        config.slow_query_threshold = Duration::from_millis(50);
        let mut manager = ApmManager::new(config);
        
        manager.start().await.unwrap();

        // 创建慢查询
        let tx_id = manager.start_transaction("db-service", "slow-query", PerformanceEventType::DatabaseQuery).await.unwrap();
        
        // 模拟慢操作
        sleep(Duration::from_millis(100)).await;
        
        manager.end_transaction(&tx_id, PerformanceStatus::Success, None).await.unwrap();

        // 等待事件处理
        sleep(Duration::from_millis(100)).await;

        let stats = manager.get_performance_stats().await;
        assert_eq!(stats.slow_queries, 1);
    }

    #[tokio::test]
    async fn test_anomaly_detection() {
        let config = AnomalyDetectionConfig::default();
        let mut detector = AnomalyDetector::new(config);

        // 添加正常值
        for i in 0..50 {
            detector.detect_anomaly("response_time", 100.0 + (i as f64));
        }

        // 添加异常值
        let is_anomaly = detector.detect_anomaly("response_time", 1000.0);
        assert!(is_anomaly);
    }
}